'use client';

import React, { useState, useEffect } from 'react';
import {
  Card,
  Tabs,
  Tab,
  Grid,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Alert,
  CircularProgress,
  Typography,
  Box,
  Divider,
  Container,
  Stack
} from '@mui/material';
import { AccessTime, BarChart, Info, CalendarMonth } from '@mui/icons-material';
import { getCheckInTime, getPersonalAttendance, getPersonalAllAttendance } from '@/lib/attendance';
import type { PersonalAttendanceRecord } from '@/lib/attendance';
import { getUserInfo } from '@/lib/user';
import Layout from '@/components/Layout';
import CalendarComponent from '@/components/CalendarComponent';
import dayjs from 'dayjs';
import moment from 'moment';
import { message } from 'antd';

interface UserInfo {
  employeeId: string;
  department: number;
  deptType: number;
}

// 定义 StatusType 类型
type StatusType = 1 | 2 | 3 | 4 | 5 | 6;

// 更新 AttendanceRecord 类型
type AttendanceRecord = Omit<PersonalAttendanceRecord, 'checkInStatus'> & {
  checkInStatus: StatusType;
};

const AttendancePage = () => {
  const [activeTab, setActiveTab] = useState(0);
  const [currentDate, setCurrentDate] = useState('');
  const [currentTime, setCurrentTime] = useState('');
  const [canCheckInToday, setCanCheckInToday] = useState(false);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [personalAttendance, setPersonalAttendance] = useState<any>(null);
  const [recentRecords, setRecentRecords] = useState<AttendanceRecord[]>([]);
  const [allRecords, setAllRecords] = useState<AttendanceRecord[]>([]);

  const columns = [
    { id: 'checkInDate', label: '日期' },
    { id: 'onWorkTime', label: '上班时间' },
    { id: 'offDutyTime', label: '下班时间' },
    { id: 'workingTime', label: '工作时长' },
    { id: 'overTime', label: '加班时间' },
    { id: 'checkInStatus', label: '状态', format: (value: number) => getStatusText(value) },
    { id: 'circumstance', label: '特殊情况', format: (value: number) => getCircumstanceText(value) },
  ];

  const statusMapping = {
    1: { text: '上班中', class: 'working', color: '#1890ff' },
    2: { text: '已下班', class: 'off-work', color: '#52c41a' },
    3: { text: '未打卡', class: 'not-checked', color: '#ff4d4f' },
    4: { text: '迟到', class: 'late', color: '#faad14' },
    5: { text: '早退', class: 'early-leave', color: '#faad14' },
    6: { text: '迟到加早退', class: 'late-early-leave', color: '#ff4d4f' },
  };

  const circumstanceMapping = {
    1: { text: '正常', color: '#52c41a' },
    2: { text: '请假', color: '#faad14' },
    3: { text: '出差', color: '#1890ff' },
    4: { text: '培训', color: '#1890ff' }
  };

  const getStatusText = (status: number) => {
    const statusInfo = statusMapping[status as keyof typeof statusMapping];
    return statusInfo ? (
      <Typography sx={{ color: statusInfo.color, fontWeight: 'medium' }}>
        {statusInfo.text}
      </Typography>
    ) : '未知';
  };

  const getCircumstanceText = (circumstance: number) => {
    const circInfo = circumstanceMapping[circumstance as keyof typeof circumstanceMapping];
    return circInfo ? (
      <Typography sx={{ color: circInfo.color, fontWeight: 'medium' }}>
        {circInfo.text}
      </Typography>
    ) : '未知';
  };

  const updateCurrentTime = () => {
    const now = new Date();
    setCurrentDate(now.toLocaleDateString('zh-CN'));
    setCurrentTime(now.toLocaleTimeString('zh-CN'));
  };

  const checkIfCanCheckInToday = async () => {
    try {
      if (!userInfo?.department || !userInfo?.deptType) {
        console.error('部门信息不存在:', userInfo);
        return;
      }
      const response = await getCheckInTime({ 
        deptId: userInfo.department, 
        deptType: userInfo.deptType 
      });
      if (response.data && response.data.code === 1) {
        const today = new Date();
        const startDate = new Date(response.data.data.setStartDate);
        const endDate = new Date(response.data.data.setEndDate);
        setCanCheckInToday(today >= startDate && today <= endDate);
      }
    } catch (error) {
      console.error('检查打卡日失败:', error);
      setCanCheckInToday(false);
    }
  };

  const getPersonalAttendanceInfo = async () => {
    try {
      const response = await getPersonalAttendance();
      if (response.data && response.data.code === 1) {
        setPersonalAttendance(response.data.data);
      }
    } catch (error) {
      console.error('获取个人考勤信息失败:', error);
    }
  };

  const fetchUserInfo = async () => {
    try {
      const response = await getUserInfo();
      if (response.data && response.data.code === 1 && response.data.data) {
        setUserInfo(response.data.data);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchAttendanceRecords = async () => {
    try {
      setLoading(true);
      const response = await getPersonalAllAttendance();
      if (response.data && response.data.code === 1 && response.data.data) {
        const records = response.data.data.map((record: any) => ({
          checkInDate: record.checkInDate,
          isCheckIn: record.isCheckIn,
          onWorkTime: record.onWorkTime || '',
          offDutyTime: record.offDutyTime || '',
          workingTime: record.workingTime || '0',
          overTime: record.overTime || '0',
          checkInStatus: (record.checkInStatus || 3) as StatusType,
          circumstance: record.circumstance || 1,
        }));

        const sortedRecords = records.sort((a, b) => 
          moment(b.checkInDate).valueOf() - moment(a.checkInDate).valueOf()
        );

        setRecentRecords(sortedRecords.slice(0, 5));
        setAllRecords(sortedRecords);
      }
    } catch (error) {
      message.error('获取考勤记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    updateCurrentTime();
    const timer = setInterval(updateCurrentTime, 1000);
    fetchUserInfo();
    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    if (userInfo) {
      checkIfCanCheckInToday();
      fetchAttendanceRecords();
      getPersonalAttendanceInfo();
    }
  }, [userInfo]);

  const handleTabChange = (_: any, newValue: number) => {
    setActiveTab(newValue);
  };

  // 渲染日历单元格的内容
  const renderDateCell = (date: Date) => {
    const record = allRecords.find(r => dayjs(r.checkInDate).isSame(date, 'day'));
    if (!record) return null;

    return (
      <Box sx={{ p: 1 }}>
        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
          上班: {record.onWorkTime || '未打卡'}
        </Typography>
        <br />
        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
          下班: {record.offDutyTime || '未打卡'}
        </Typography>
        <br />
        <Typography variant="caption" sx={{ 
          color: statusMapping[record.checkInStatus as keyof typeof statusMapping]?.color || 'text.primary'
        }}>
          {statusMapping[record.checkInStatus as keyof typeof statusMapping]?.text || '未知'}
        </Typography>
      </Box>
    );
  };

  return (
    <Layout>
      <Container maxWidth="lg" sx={{ py: 3 }}>
        <Card elevation={2}>
          <Box sx={{ 
            bgcolor: 'primary.main', 
            color: 'primary.contrastText',
            p: 2,
            borderTopLeftRadius: 1,
            borderTopRightRadius: 1
          }}>
            <Typography variant="h5" component="div" sx={{ mb: 2 }}>
          考勤管理
        </Typography>
            <Box sx={{ 
              bgcolor: 'rgba(255, 255, 255, 0.1)', 
              p: 2, 
              borderRadius: 1, 
              display: 'flex', 
              alignItems: 'center' 
            }}>
              <Info sx={{ mr: 1 }} />
              <Typography>
                温馨提示：请使用微信小程序进行考勤打卡，本页面仅供查看考勤记录。
              </Typography>
            </Box>
          </Box>

        {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
          <CircularProgress />
            </Box>
          ) : (
            <>
              <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
                <Tabs 
                  value={activeTab} 
                  onChange={handleTabChange}
                  sx={{ px: 2 }}
                  variant="fullWidth"
                >
                  <Tab 
                    icon={<AccessTime />} 
                    label="考勤信息" 
                    sx={{ py: 2 }}
                  />
                  <Tab 
                    icon={<BarChart />} 
                    label="考勤统计" 
                    sx={{ py: 2 }}
                  />
          </Tabs>
              </Box>

        {!loading && (
          <>
            {activeTab === 0 && (
                    <Box sx={{ p: 3 }}>
                      <Card 
                        elevation={0} 
                        sx={{ 
                          bgcolor: 'primary.light', 
                          color: 'primary.contrastText',
                          p: 3,
                          textAlign: 'center',
                          mb: 3,
                          borderRadius: 2
                        }}
                      >
                        <CalendarMonth sx={{ fontSize: 40, mb: 1 }} />
                    <Typography variant="h6">{currentDate}</Typography>
                        <Typography variant="h3" sx={{ mt: 1 }}>{currentTime}</Typography>
                      </Card>

                      <Card 
                        elevation={1} 
                        sx={{ 
                          mb: 3,
                          borderRadius: 2,
                          overflow: 'hidden'
                        }}
                      >
                        <Box sx={{ 
                          bgcolor: 'info.light', 
                          p: 2,
                          borderBottom: '1px solid',
                          borderColor: 'divider'
                        }}>
                          <Typography variant="h6" sx={{ color: 'info.dark' }}>
                            今日考勤状态
                          </Typography>
                        </Box>
                        <Box sx={{ p: 2 }}>
                          {!canCheckInToday && (
                            <Typography variant="body1" sx={{ color: 'text.secondary' }}>
                              今日无需打卡
                            </Typography>
                          )}
                          {canCheckInToday && personalAttendance && (
                            <Stack spacing={2}>
                              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <Typography variant="body1">上班时间</Typography>
                                <Typography variant="body1" sx={{ color: 'text.secondary' }}>
                                  {personalAttendance.onWorkTime || '未打卡'}
                                </Typography>
                              </Box>
                              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <Typography variant="body1">下班时间</Typography>
                                <Typography variant="body1" sx={{ color: 'text.secondary' }}>
                                  {personalAttendance.offDutyTime || '未打卡'}
                                </Typography>
                              </Box>
                              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <Typography variant="body1">考勤状态</Typography>
                                <Typography 
                                  variant="body1" 
                                  sx={{ 
                                    color: personalAttendance.isCheckIn === 1 ? 'success.main' : 'error.main',
                                    fontWeight: 'bold'
                                  }}
                                >
                                  {personalAttendance.isCheckIn === 1 ? '已签到' : '未签到'}
                                </Typography>
                              </Box>
                            </Stack>
                          )}
                        </Box>
                      </Card>

                      <Card elevation={1} sx={{ borderRadius: 2, overflow: 'hidden' }}>
                        <Box sx={{ 
                          bgcolor: 'grey.100', 
                          p: 2,
                          borderBottom: '1px solid',
                          borderColor: 'divider'
                        }}>
                          <Typography variant="h6" sx={{ color: 'text.primary' }}>
                            最近考勤记录
                          </Typography>
                        </Box>
                        <TableContainer>
                      <Table>
                        <TableHead>
                          <TableRow>
                            {columns.map((column) => (
                                  <TableCell 
                                    key={column.id}
                                    sx={{ 
                                      bgcolor: 'grey.50',
                                      fontWeight: 'bold'
                                    }}
                                  >
                                    {column.label}
                                  </TableCell>
                            ))}
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          {recentRecords.map((row) => (
                                <TableRow 
                                  key={row.checkInDate}
                                  hover
                                >
                              {columns.map((column) => (
                                <TableCell key={column.id}>
                                  {column.format ? column.format(row[column.id]) : row[column.id]}
                                </TableCell>
                              ))}
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </TableContainer>
                      </Card>
                    </Box>
            )}
            {activeTab === 1 && (
                    <Box sx={{ p: 3 }}>
                      <Card elevation={1} sx={{ borderRadius: 2, overflow: 'hidden' }}>
                        <CalendarComponent 
                          attendanceRecords={allRecords}
                          renderDateCell={renderDateCell}
                        />
                      </Card>
                    </Box>
                  )}
                </>
            )}
          </>
        )}
      </Card>
      </Container>
    </Layout>
  );
};

export default AttendancePage;